package com.example.agent;

import javassist.*;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.AttributeInfo;
import javassist.bytecode.annotation.Annotation;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Objects;

public class PrintOutTransformer implements ClassFileTransformer {
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        // 将斜杠替换为点，比如：java/lang/Class$MethodArray
        className = className.replace("/", ".");
        try {
            ClassPool pool = ClassPool.getDefault();
            CtClass cc = null;
            try {
                cc = pool.get(className);
            } catch (Exception e) {
                // 找不到类，直接返回原始字节码
                return classfileBuffer;
            }
            // 类里边的方法列表
            CtMethod[] personFlies = cc.getDeclaredMethods();
            AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) cc.getClassFile().getAttribute(AnnotationsAttribute.visibleTag);
            Annotation annotation = annotationsAttribute.getAnnotation("org.springframework.web.bind.annotation.RestController");
            if (Objects.nonNull(annotation)) {
                //借助JavaAssist工具，进行字节码插桩
                for (CtMethod personFly : personFlies) {
                    if (!Objects.equals(personFly.getModifiers(), AccessFlag.PUBLIC)) {
                        //如果不是public方法，则跳过
                        continue;
                    }
                    //定义局部变量
                    personFly.addLocalVariable("_start", CtClass.longType);
                    personFly.addLocalVariable("_end", CtClass.longType);
                    //在目标方法前后，插入代码
                    personFly.insertBefore("_start = System.currentTimeMillis();");
                    personFly.insertAfter("_end = System.currentTimeMillis();System.out.println(\"接口耗时：\" + (_end-_start));", true);
                }
                cc.detach();
                return cc.toBytecode();
            }
            return null;
        } catch (CannotCompileException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
